package ua.kpi.ipsa.expert.api.algorithm;

import java.lang.reflect.*;
import java.util.*;

import ua.kpi.ipsa.expert.api.db.*;

/**
 * 
 * @author doctorpro
 */
public class AlgoLoaf {

	private DAO dao;

	public Map<Integer, Algorithm> m = new HashMap<Integer, Algorithm>();

	private final CodePresentationManager presentationManager;

	/**
	 * 
	 * @param dao
	 * @param presentationManager
	 */
	public AlgoLoaf(DAO dao, CodePresentationManager presentationManager) {
		this.presentationManager = presentationManager;
		this.dao = dao;
	}

	/**
	 * 
	 * @param algoId
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SecurityException
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 */
	public Algorithm getAlgorithm(int algoId) throws DataAccessException,
			ClassNotFoundException, NoSuchMethodException, SecurityException,
			InstantiationException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException {

		Algorithm result = m.get(algoId);

		if (result == null) {
			result = (Algorithm) Class
					.forName(dao.getAlgorithm(algoId).className)
					.getConstructor(DAO.class).newInstance(dao);
			m.put(algoId, result);
			presentationManager.addAlgorithmPresentations(result);
		}

		return result;
	}
}
